package net.bithappens.hnqe.mapper.graphxml;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import net.bithappens.hnqe.mapper.OperationInstructions;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PropertyLoader {

	private Logger log = Logger.getLogger(this.getClass());
	
	public static PropertyBean loadProperties() throws Exception{
		
		URL url = ClassLoader.getSystemResource("xmlMapperConfig.xml");
		
		File configFile = new File(url.toURI());

		DocumentBuilder documentBuilder;
		
		documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		
		Document doc = documentBuilder.parse(configFile);
		
		doc.getDocumentElement().normalize();
		
		PropertyBean propertyBean = new PropertyBean();
		
		propertyBean.setMapperId(doc.getDocumentElement().getAttribute("mapperId"));
		
		propertyBean.setInstanceConfigs(parseInstances(doc.getElementsByTagName("instance")));
		
		return propertyBean;
		
	}
	
	
	private static Collection<InstanceConfigBean> parseInstances(NodeList nodeList) {
		
		Collection<InstanceConfigBean> instancelist = new ArrayList<InstanceConfigBean>(); 
		
		for (int s = 0; s < nodeList.getLength(); s++) {
			
			Node node = nodeList.item(s);
			
			InstanceConfigBean config = new InstanceConfigBean();
			
			config.setInstanceId(node.getAttributes().getNamedItem("name").getNodeValue());
			
			config.setRefreshIntervall(Long.valueOf(node.getAttributes().getNamedItem("refreshIntervall").getNodeValue()));
			
			NodeList instanceSettings = node.getChildNodes();
			
			for (int i = 0; i < instanceSettings.getLength(); i++) {
			
				Node setting = instanceSettings.item(i);
				
				if(setting.getNodeType() == Node.ELEMENT_NODE){
					
					if("source".equals(setting.getNodeName())){
						
						config.setSourcePath(setting.getAttributes().getNamedItem("path").getNodeValue());
						
					} else {
						
						OperationInstructions operationInstructions = new OperationInstructions(
								Boolean.valueOf(setting.getAttributes().getNamedItem("clearIfExist").getNodeValue()),
								Boolean.valueOf(setting.getAttributes().getNamedItem("enableKeyMatch").getNodeValue())
							);
					
						config.setInstructions(operationInstructions);
					}										
				}
			}
			
			instancelist.add(config);
		}
		
		return instancelist;
	}
	
}
